﻿// Copyright (C) 2009 - 2013 EvTech Project
//
// This program is free software: you can redistribute it and/or modify
// it under the +terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/. 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Piirto
{
    public partial class SelectCharacterForm : Form
    {
        private List<Character> characterList;
        private int currentPage;
        private Character selected;
        private const string SAVEFILEPATH = "./data";
        private const string SAVEFILENAME = "characters.dat";
        private const char DELIMETER = ',';

        private EditCharacterForm editForm;

        public SelectCharacterForm()
        {
            InitializeComponent();
            try
            {
                if (!Directory.Exists(SAVEFILEPATH))
                {
                    Directory.CreateDirectory(SAVEFILEPATH);
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }

            editForm = new EditCharacterForm();
            characterList = new List<Character>();
            for (int i = 0; i < 6; i++)
            {
                SpriteControl sprCtrl = new SpriteControl();
                //pbox.SizeMode = PictureBoxSizeMode.Zoom;
                //pbox.Image = null;
                sprCtrl.CharacterSelected += new EventHandler(sprCtrl_Click);
                sprCtrl.CharacterEditSelected += new EventHandler(sprCtrl_EditClick);
                this.tableLayoutPanel1.Controls.Add(sprCtrl);
                sprCtrl.Dock = DockStyle.Fill;
            }
            try
            {
                Character carCharacter = new Character(global::Piirto.Properties.Resources.car, "./sounds/jeep_horn.wav",
                    "./sounds/default_crash.wav", "./sounds/engine_old.wav");
                carCharacter.getSprite().setSize(40);
                characterList.Add(carCharacter);

                Character trainCharacter = new Character(global::Piirto.Properties.Resources.train, "./sounds/train_whistle.wav",
                    "./sounds/default_crash.wav", "./sounds/steam_train_run.wav");
                trainCharacter.getSprite().setSize(40);
                characterList.Add(trainCharacter);

                Character horseCharacter = new Character(global::Piirto.Properties.Resources.horse, "./sounds/horse_whinnying.wav",
                    "./sounds/default_crash.wav", "./sounds/horse_walking.wav");
                horseCharacter.getSprite().setSize(40);
                characterList.Add(horseCharacter);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
            if (characterList.Count > 0)
            {
                selected = characterList.ElementAt(0);
            }
            loadCharacters();
            setImages();
        }

        private void loadCharacters()
        {
            if (File.Exists(Path.Combine(SAVEFILEPATH, SAVEFILENAME)))
            {
                TextReader reader = null;
                try
                {
                    reader = new StreamReader(Path.Combine(SAVEFILEPATH, SAVEFILENAME));
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] elements = line.Split(DELIMETER);
                        Console.Out.WriteLine("Reading line \"" + line + "\" from " + SAVEFILENAME);
                        if (elements.Length == 4)
                        {
                            try
                            {
                                Image img = Image.FromFile(elements[0]);
                                Character character = new Character(img, elements[1],
                                    elements[2], elements[3], true);
                                character.getSprite().setSize(40);
                                character.setImagepath(elements[0]);
                                characterList.Add(character);
                            }
                            catch (Exception)
                            {
                                Console.Out.WriteLine("Error in reading line " + elements.ToString());
                            }
                        }
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    Console.Out.WriteLine(ex.Message);
                }
            }
        }

        private void saveCharacters()
        {
            TextWriter writer = null;
            try
            {
                writer = new StreamWriter(Path.Combine(SAVEFILEPATH, SAVEFILENAME));
                for (int i = 3; i < characterList.Count; i++)
                {
                    Character ch = characterList[i];
                    string line = ch.getImagepath() + DELIMETER + ch.getWinsound().SoundLocation +
                        DELIMETER + ch.getCrashsound().SoundLocation +
                        DELIMETER + ch.getMovesound().SoundLocation;
                    Console.Out.WriteLine("Writing line \"" + line + "\" to " + SAVEFILENAME);
                    writer.WriteLine(line);
                }
                writer.Close();
            }
            catch (Exception ex)
            {
                if (writer != null)
                {
                    writer.Close();
                }
                Console.Out.WriteLine(ex.Message);
            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            currentPage--;
            setImages();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            editForm.setCharacter(null);
            if(editForm.ShowDialog()==DialogResult.OK)
            {
                selected = editForm.getCharacter();
                characterList.Add(selected);
                setImages();
                saveCharacters();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            currentPage++;
            setImages();
        }

        private void setImages()
        {
            for (int i = 0; i < this.tableLayoutPanel1.Controls.Count; i++)
            {
                if (currentPage * 6 + i < characterList.Count)
                {
                    ((SpriteControl)this.tableLayoutPanel1.Controls[i]).
                        setCharacter(characterList.ElementAt(currentPage * 6 + i)); 
                }
                else
                {
                    ((SpriteControl)this.tableLayoutPanel1.Controls[i]).setCharacter(null);
                }
            }
            if (currentPage > 0)
            {
                btnPrev.Visible = true;
            }
            else
            {
                btnPrev.Visible = false;
            }
            if ((currentPage + 1) * 6 < characterList.Count)
            {
                btnNext.Visible = true;
            }
            else
            {
                btnNext.Visible = false;
            }
        }

        private void sprCtrl_Click(object sender, EventArgs e)
        {
            SpriteControl sc = sender as SpriteControl;
            if (sc != null && sc.getCharacter() != null)
            {
                selected = ((SpriteControl)sender).getCharacter();
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        private void sprCtrl_EditClick(object sender, EventArgs e)
        {
            SpriteControl sc = sender as SpriteControl;
            if (sc != null && sc.getCharacter() != null)
            {
                editForm.setCharacter(sc.getCharacter());
                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    Console.Out.WriteLine("editForm.ShowDialog() == DialogResult.OK");
                    selected = editForm.getCharacter();
                    setImages();
                    saveCharacters();
                }
            }
        }

        private void SelectSpriteForm_Resize(object sender, EventArgs e)
        {
            int scaleX = this.Width / 100;
            int scaleY = this.Height / 100;
            tableLayoutPanel1.SetBounds(5 * scaleX, 5 * scaleY, 90 * scaleX, 70 * scaleY);
            btnPrev.SetBounds(5 * scaleX, 80 * scaleY, 25 * scaleX, 15 * scaleY);
            btnNext.SetBounds(70 * scaleX, 80 * scaleY, 25 * scaleX, 15 * scaleY);
            btnNew.SetBounds((int)(37.5 * scaleX), 80 * scaleY, 25 * scaleX, 15 * scaleY);
        }

        public Character getSelected()
        {
            return selected;
        }
    }
}
